import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class NetWorkCase extends StatefulWidget {
  const NetWorkCase({ super.key });

  @override
  _NetWorkCase createState() => _NetWorkCase();
}

class _NetWorkCase extends State<NetWorkCase> {
  @override
  void initState() {
    // 发起网络请求
    getOrdersData();
    // TODO: implement initState
    super.initState();
  }
  List<OrdersItem>  list = [];
  // 发起异步请求
  getOrdersData () async {
    print('开始请求');
    try {
       const BASEURL = "https://mock.boxuegu.com/mock";
    Dio dio = Dio(); // 创建一个dio的网络请求对象 等同于鸿蒙的axios.create() http.createHttp()
    var res = await dio.get("$BASEURL/1172/orders");
    List tempList = res.data as List;
    for (var item in tempList) {
      list.add( OrdersItem(
        createTime: item["createTime"],
        orderState: item["orderState"],
        image: item["image"],
        curPrice: item["curPrice"],
        totalNum: item["totalNum"],
        totalMoney: item["totalMoney"],
        attrsText: item["attrsText"],
         name: item["name"],
       ));
    }
    // 更新数据
     setState(() {
       
     });
    
    } catch (e) {
      print(e);
    }
   
  }
// 循环渲染内容
Widget getListItem (int index) {
  return Container(
    padding: const EdgeInsets.all(10),
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Image.network(list[index].image,
         width: 100,
         height: 100,
         fit: BoxFit.cover,
        ),
        Container(
          height: 100,
          margin: const EdgeInsets.only(left: 20),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
             crossAxisAlignment: CrossAxisAlignment.start,
            children: [
            Text(list[index].name, 
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 20
            ),),
            Text("¥${list[index].curPrice.toString()}" , 
            style: const TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.red,
                fontSize: 14
            ))
          ],
        ) ,
        )
       

      ],
    ),
  );
}

  @override
  Widget build(BuildContext context) {
    return Container(
      child: ListView.builder(itemBuilder: (BuildContext context, int index) {
        return getListItem(index);
    

      },
      itemCount: list.length,
      ),
    );
  }
}

// 鸿蒙 json字符串 => JSON.parse(any) as 任何类型
class OrdersItem {
   String createTime = "";
   int orderState = 0;
   String image = "";
   int  totalNum = 0;
   double curPrice = 0.0;
   double totalMoney = 0.0;
   String attrsText = "";
   String name = "";

   OrdersItem({ 
     required this.createTime,
     required this.orderState,
     required this.image,
     required this.totalNum,
     required this.curPrice,
     required this.totalMoney,
     required this.attrsText,
     required this.name
    });
}